import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);


export default new Vuex.Store({
  state: {
    user: null,
    users: [
      {
        id: 1,
        username: "admin",
        password: "admin123",
        role: "admin"
      },
      {
        id: 2,
        username: "user1",
        password: "user123",
        role: "user"
      },
      {
        id: 3,
        username: "user2",
        password: "user123",
        role: "user"
      }
    ],

    cabinets: {
      areas: ["A", "B", "C"],
      rows: {
        A: ["1", "2", "3"],
        B: ["1", "2", "3"],
        C: ["1", "2", "3"]
      },
      cabinets: {
        "A-1-1": { id: "A-1-1", status: "in_use", password: null, startTime: "2023-10-27T09:00:00.000Z", userId: 3, username: "user2", area: "A", row: "1", number: "1" },
        "A-1-2": { id: "A-1-2", status: "available", password: null, startTime: null, userId: null, username: null, area: "A", row: "1", number: "2" },
        "A-1-3": { id: "A-1-3", status: "available", password: null, startTime: null, userId: null, username: null, area: "A", row: "1", number: "3" },
        "A-2-1": { id: "A-2-1", status: "available", password: null, startTime: null, userId: null, username: null, area: "A", row: "2", number: "1" },
        "A-2-2": { id: "A-2-2", status: "available", password: null, startTime: null, userId: null, username: null, area: "A", row: "2", number: "2" },
        "A-2-3": { id: "A-2-3", status: "available", password: null, startTime: null, userId: null, username: null, area: "A", row: "2", number: "3" },
        "A-3-1": { id: "A-3-1", status: "available", password: null, startTime: null, userId: null, username: null, area: "A", row: "3", number: "1" },
        "A-3-2": { id: "A-3-2", status: "available", password: null, startTime: null, userId: null, username: null, area: "A", row: "3", number: "2" },
        "A-3-3": { id: "A-3-3", status: "available", password: null, startTime: null, userId: null, username: null, area: "A", row: "3", number: "3" },
        "B-1-1": { id: "B-1-1", status: "available", password: null, startTime: null, userId: null, username: null, area: "B", row: "1", number: "1" },
        "B-1-2": { id: "B-1-2", status: "available", password: null, startTime: null, userId: null, username: null, area: "B", row: "1", number: "2" },
        "B-1-3": { id: "B-1-3", status: "available", password: null, startTime: null, userId: null, username: null, area: "B", row: "1", number: "3" },
        "B-2-1": { id: "B-2-1", status: "in_use", password: null, startTime: "2024-10-24T10:00:00.000Z", userId: 3, username: "user2", area: "B", row: "2", number: "1" },
        "B-2-2": { id: "B-2-2", status: "available", password: null, startTime: null, userId: null, username: null, area: "B", row: "2", number: "2" },
        "B-2-3": { id: "B-2-3", status: "available", password: null, startTime: null, userId: null, username: null, area: "B", row: "2", number: "3" },
        "B-3-1": { id: "B-3-1", status: "available", password: null, startTime: null, userId: null, username: null, area: "B", row: "3", number: "1" },
        "B-3-2": { id: "B-3-2", status: "available", password: null, startTime: null, userId: null, username: null, area: "B", row: "3", number: "2" },
        "B-3-3": { id: "B-3-3", status: "available", password: null, startTime: null, userId: null, username: null, area: "B", row: "3", number: "3" },
        "C-1-1": { id: "C-1-1", status: "available", password: null, startTime: null, userId: null, username: null, area: "C", row: "1", number: "1" },
        "C-1-2": { id: "C-1-2", status: "available", password: null, startTime: null, userId: null, username: null, area: "C", row: "1", number: "2" },
        "C-1-3": { id: "C-1-3", status: "available", password: null, startTime: null, userId: null, username: null, area: "C", row: "1", number: "3" },
        "C-2-1": { id: "C-2-1", status: "available", password: null, startTime: null, userId: null, username: null, area: "C", row: "2", number: "1" },
        "C-2-2": { id: "C-2-2", status: "available", password: null, startTime: null, userId: null, username: null, area: "C", row: "2", number: "2" },
        "C-2-3": { id: "C-2-3", status: "available", password: null, startTime: null, userId: null, username: null, area: "C", row: "2", number: "3" },
        "C-3-1": { id: "C-3-1", status: "available", password: null, startTime: null, userId: null, username: null, area: "C", row: "3", number: "1" },
        "C-3-2": { id: "C-3-2", status: "available", password: null, startTime: null, userId: null, username: null, area: "C", row: "3", number: "2" },
        "C-3-3": { id: "C-3-3", status: "available", password: null, startTime: null, userId: null, username: null, area: "C", row: "3", number: "3" }
      }
    },
    records: [
      // Example Records (模拟真实用户使用情况)
      {
        id: 1,
        cabinetId: "A-1-1",
        userId: 2,
        username: "user1",
        startTime: "2023-10-20T08:00:00.000Z",
        endTime: "2023-10-20T09:30:00.000Z",
        status: "completed"
      },
      {
        id: 2,
        cabinetId: "B-2-1",
        userId: 2,
        username: "user1",
        startTime: "2023-10-20T11:00:00.000Z",
        endTime: "2023-10-20T12:00:00.000Z",
        status: "completed"
      },
      {
        id: 3,
        cabinetId: "A-3-2",
        userId: 2,
        username: "user1",
        startTime: "2023-10-20T14:00:00.000Z",
        endTime: "2023-10-20T15:30:00.000Z",
        status: "completed"
      },
      {
        id: 4,
        cabinetId: "C-1-1",
        userId: 3,
        username: "user2",
        startTime: "2023-10-21T09:00:00.000Z",
        endTime: "2023-10-21T10:00:00.000Z",
        status: "completed"
      },
      {
        id: 5,
        cabinetId: "A-1-2",
        userId: 3,
        username: "user2",
        startTime: "2023-10-21T13:00:00.000Z",
        endTime: "2023-10-21T14:00:00.000Z",
        status: "completed"
      },
      {
        id: 6,
        cabinetId: "B-3-3",
        userId: 3,
        username: "user2",
        startTime: "2023-10-21T16:00:00.000Z",
        endTime: "2023-10-21T17:00:00.000Z",
        status: "completed"
      },
      {
        id: 7,
        cabinetId: "A-2-2",
        userId: 1,
        username: "admin",
        startTime: "2023-10-22T10:00:00.000Z",
        endTime: "2023-10-22T11:00:00.000Z",
        status: "completed"
      },
      {
        id: 8,
        cabinetId: "C-2-1",
        userId: 1,
        username: "admin",
        startTime: "2023-10-22T14:00:00.000Z",
        endTime: "2023-10-22T15:00:00.000Z",
        status: "completed"
      },
      {
        id: 9,
        cabinetId: "B-1-1",
        userId: 1,
        username: "admin",
        startTime: "2023-10-22T18:00:00.000Z",
        endTime: "2023-10-22T19:00:00.000Z",
        status: "completed"
      },
      {
        id: 10,
        cabinetId: "A-1-1",
        userId: 2,
        username: "user1",
        startTime: "2023-10-23T09:00:00.000Z",
        endTime: "2023-10-23T10:30:00.000Z",
        status: "completed"
      },
      {
        id: 11,
        cabinetId: "C-3-1",
        userId: 2,
        username: "user1",
        startTime: "2023-10-23T11:30:00.000Z",
        endTime: "2023-10-23T12:30:00.000Z",
        status: "completed"
      },
      {
        id: 12,
        cabinetId: "B-2-2",
        userId: 2,
        username: "user1",
        startTime: "2023-10-23T15:00:00.000Z",
        endTime: "2023-10-23T16:00:00.000Z",
        status: "completed"
      },
      {
        id: 13,
        cabinetId: "A-1-1",
        userId: 3,
        username: "user2",
        startTime: "2023-10-24T08:30:00.000Z",
        endTime: "2023-10-24T09:45:00.000Z",
        status: "completed"
      },
      {
        id: 14,
        cabinetId: "A-3-2",
        userId: 3,
        username: "user2",
        startTime: "2023-10-24T14:30:00.000Z",
        endTime: "2023-10-24T16:00:00.000Z",
        status: "completed"
      },
      {
        id: 15,
        cabinetId: "C-1-1",
        userId: 1,
        username: "admin",
        startTime: "2023-10-25T09:15:00.000Z",
        endTime: "2023-10-25T10:15:00.000Z",
        status: "completed"
      },
      {
        id: 16,
        cabinetId: "A-1-2",
        userId: 1,
        username: "admin",
        startTime: "2023-10-25T13:30:00.000Z",
        endTime: "2023-10-25T14:30:00.000Z",
        status: "completed"
      },
      {
        id: 17,
        cabinetId: "B-3-3",
        userId: 1,
        username: "admin",
        startTime: "2023-10-25T16:30:00.000Z",
        endTime: "2023-10-25T17:30:00.000Z",
        status: "completed"
      },
      {
        id: 18,
        cabinetId: "A-2-2",
        userId: 2,
        username: "user1",
        startTime: "2023-10-26T10:00:00.000Z",
        endTime: "2023-10-26T11:00:00.000Z",
        status: "completed"
      },
      {
        id: 19,
        cabinetId: "C-2-1",
        userId: 2,
        username: "user1",
        startTime: "2023-10-26T14:00:00.000Z",
        endTime: "2023-10-26T15:00:00.000Z",
        status: "completed"
      },
      {
        id: 20,
        cabinetId: "B-1-1",
        userId: 2,
        username: "user1",
        startTime: "2023-10-26T18:00:00.000Z",
        endTime: "2023-10-26T19:00:00.000Z",
        status: "completed"
      },
      {
        id: 21,
        cabinetId: "C-3-1",
        userId: 3,
        username: "user2",
        startTime: "2023-10-27T11:00:00.000Z",
        endTime: "2023-10-27T12:00:00.000Z",
        status: "completed"
      },
      {
        id: 22,
        cabinetId: "B-2-2",
        userId: 3,
        username: "user2",
        startTime: "2023-10-27T15:00:00.000Z",
        endTime: "2023-10-27T16:00:00.000Z",
        status: "completed"
      }
    ]
  },
  mutations: {
    SET_USER(state, user) {
      state.user = user;
    },
    ADD_USER(state, user) {
      state.users.push(user);
    },
    UPDATE_USER_ROLE(state, { userId, role }) {
      const user = state.users.find(u => u.id === userId);
      if (user) {
        user.role = role;
      }
    },
    DELETE_USER(state, userId) {
      state.users = state.users.filter(u => u.id !== userId);
    },
    ADD_RECORD(state, { id, cabinetId, userId, username, startTime, endTime, status }) {
      // 使用 Vue.set 确保响应式更新
      state.records.push({
        id,
        cabinetId,
        userId,
        username,
        startTime,
        endTime,
        status
      });
      // 强制更新数组以触发响应式
      state.records = [...state.records];
    },
    SET_CABINET_STATUS(state, { cabinetId, status, userId, password, startTime }) {
      const cabinet = state.cabinets.cabinets[cabinetId];
      if (cabinet) {
        cabinet.status = status;
        cabinet.userId = userId;
        cabinet.password = password;
        cabinet.startTime = startTime;
      }
    },
    ADD_CABINET(state, cabinet) {
      Vue.set(state.cabinets.cabinets, cabinet.id, cabinet);
    },
    REMOVE_CABINET(state, cabinetId) {
      delete state.cabinets.cabinets[cabinetId];
    },
    ADD_AREA(state, area) {
      if (!state.cabinets.areas.includes(area)) {
        state.cabinets.areas.push(area);
        Vue.set(state.cabinets.rows, area, []);
      }
    },
    ADD_ROW(state, { area, row }) {
      if (state.cabinets.rows[area] && !state.cabinets.rows[area].includes(row)) {
        state.cabinets.rows[area].push(row);
      }
    }
  },
  actions: {
    // 用户认证相关
    async login({ commit, state }, { username, password, role }) {
      const user = state.users.find(
        u => u.username === username && u.password === password && u.role === role
      );
      if (user) {
        // 模拟 JWT/Session 存储
        localStorage.setItem('currentUser', JSON.stringify(user));
        commit("SET_USER", { ...user });
        return user;
      }
      throw new Error("用户名、密码或角色错误");
    },
    async register({ commit, state }, { username, password }) {
      // 检查用户名是否已存在
      if (state.users.some(u => u.username === username)) {
        throw new Error("用户名已存在");
      }

      // 创建新用户
      const newUser = {
        id: state.users.length + 1,
        username,
        password,
        role: "user" // 默认角色为普通用户
      };

      commit("ADD_USER", newUser);
      return newUser;
    },
    logout({ commit }) {
      localStorage.removeItem('currentUser');
      commit("SET_USER", null);
    },
    // 用户管理相关
    updateUserRole({ commit }, { userId, role }) {
      commit("UPDATE_USER_ROLE", { userId, role });
    },
    deleteUser({ commit, state }, userId) {
      // 不允许删除当前登录用户
      if (state.user && state.user.id === userId) {
        throw new Error("不能删除当前登录用户");
      }
      commit("DELETE_USER", userId);
    },
    // 柜子操作相关
    async useCabinet({ commit, state }, { cabinetId, userId }) {
      const cabinet = state.cabinets.cabinets[cabinetId];
      if (!cabinet) {
        throw new Error("柜子不存在");
      }
      if (cabinet.status !== "available") {
        throw new Error("柜子不可用");
      }

      // 查找当前用户信息以获取用户名
      const currentUser = state.users.find(user => user.id === userId);
      if (!currentUser) {
        throw new Error("用户不存在");
      }

      const password = Math.random().toString(36).slice(-6);
      const startTime = new Date().toISOString();

      // 更新柜子状态，使用当前登录用户的用户名
      commit("SET_CABINET_STATUS", {
        cabinetId,
        status: "in_use",
        userId: userId,
        username: currentUser.username,  // 使用当前登录用户的用户名
        password,
        startTime
      });

      // 创建新的使用记录，使用当前登录用户的用户名
      const newRecord = {
        id: Date.now(),
        cabinetId,
        userId: userId,
        username: currentUser.username,  // 使用当前登录用户的用户名
        startTime,
        endTime: null,
        status: "in_use"
      };

      // 添加使用记录
      commit("ADD_RECORD", newRecord);

      return { password, startTime };
    },
    async releaseCabinet({ commit, state }, { cabinetId, password }) {
      const cabinet = state.cabinets.cabinets[cabinetId];
      if (!cabinet) {
        throw new Error("柜子不存在");
      }
      if (cabinet.status !== "in_use") {
        throw new Error("柜子未被使用");
      }
      if (cabinet.userId !== state.user.id && state.user.role !== "admin") {
        throw new Error("无权操作此柜子");
      }
      if (cabinet.password !== password && state.user.role !== "admin") {
        throw new Error("密码错误");
      }

      const endTime = new Date().toISOString();
      commit("SET_CABINET_STATUS", {
        cabinetId,
        status: "available",
        userId: null,
        password: null,
        startTime: null
      });

      // 更新使用记录
      const record = state.records.find(
        r => r.cabinetId === cabinetId && r.status === "in_use"
      );
      if (record) {
        record.endTime = endTime;
        record.status = "completed";
      }
    },
    // 柜子管理相关
    addCabinet({ commit, state }, { area, row, number }) {
      const cabinetId = `${area}-${row}-${number}`;


      if (state.cabinets.cabinets[cabinetId]) {
        throw new Error(`柜子 ${cabinetId} 已存在`);
      }

      const cabinet = {
        id: cabinetId,
        status: "available",
        password: null,
        startTime: null,
        userId: null,
        username: null,
        area: area,
        row: row,
        number: number
      };
      commit("ADD_CABINET", cabinet);
      return cabinet;
    },
    removeCabinet({ commit, state }, cabinetId) {
      const cabinet = state.cabinets.cabinets[cabinetId];
      if (!cabinet) {
        throw new Error("柜子不存在");
      }
      if (cabinet.status === "in_use") {
        throw new Error("柜子正在使用中，无法删除");
      }
      commit("REMOVE_CABINET", cabinetId);
    },
    addArea({ commit }, area) {
      commit("ADD_AREA", area);
    },
    addRow({ commit }, { area, row }) {
      commit("ADD_ROW", { area, row });
    }
  },
  getters: {
    isAuthenticated: state => !!state.user,
    isAdmin: state => state.user && state.user.role === "admin",
    userCabinets: state => {
      if (!state.user) return [];
      return Object.values(state.cabinets.cabinets).filter(
        cabinet => cabinet.userId === state.user.id
      );
    },
    availableCabinets: state => {
      return Object.values(state.cabinets.cabinets).filter(
        cabinet => cabinet.status === "available"
      );
    },
    userRecords: state => {
      if (!state.user) return [];
      // 返回按时间倒序排列的用户记录
      return [...state.records]
        .filter(record => record.userId === state.user.id)
        .sort((a, b) => new Date(b.startTime) - new Date(a.startTime));
    },
    getCabinetRecords: (state) => {
      // 返回按时间倒序排列的所有记录
      return [...state.records]
        .sort((a, b) => new Date(b.startTime) - new Date(a.startTime));
    },
    getAllCabinets: (state) => {
      // 获取所有柜子数据并返回数组
      return Object.values(state.cabinets.cabinets);
    },
    getCabinetsByRow: (state) => (area, row) => {
      // 过滤出指定区域和排的柜子
      return Object.values(state.cabinets.cabinets).filter(cabinet =>
        cabinet.id.startsWith(`${area}-${row}-`)
      );
    },
    getCabinetById: (state) => (cabinetId) => {
      // 根据柜子ID获取单个柜子对象
      return state.cabinets.cabinets[cabinetId];
    }
  }
});
